<script setup lang="ts">
import { defineProps, computed, inject, ComponentInternalInstance } from 'vue'
import { getOperaOptions } from '../utils/opera'
import { get, cloneDeep } from 'lodash-unified'

const tableRoot = inject<ComponentInternalInstance>('tableRoot')
const tableProps = inject<YTableProps>('tableProps')
const tableScopeEvents = inject<any>('tableScopeEvents')

const props = defineProps({
  options: { type: [Array, Object] as PropType<YTableOperas>, required: true }
})

const options = computed(() => getOperaOptions(props.options))

const handler = {
  add: () => {
    tableScopeEvents.emit('add-row', {})
  },
  delete: async () => {
    const selectRows = await tableRoot.exposed.getCheckRecords(false)
    tableScopeEvents.emit('delete-row', selectRows)
  },
  fill: async () => {
    const column = tableRoot.exposed.vxe().getEditRecord()?.column || tableRoot.exposed.vxe()?.getSelectedCell()?.column
    const rowIndex = tableRoot.exposed.vxe().getEditRecord()?.$rowIndex
    await tableRoot.exposed.vxe().clearEdit()

    const data = tableRoot.exposed.vxe().getData()
    const row = data[rowIndex]
    tableScopeEvents.emit('fill-column', { field: column.id, value: row[column.id], rowIndex })
  },
  copy: async () => {
    // 选中行
    const select = await tableRoot.exposed.getCheckRecord(true)

    const newRow = cloneDeep(select)
    delete newRow.id
    delete newRow._id

    tableScopeEvents.emit('add-row', newRow)
  },
  drag: () => {
    tableScopeEvents.emit('row-drag')
  }
}

const handClick = (item: YTableOperaOption) => {
  if (!item.trigger) return;

  const filter = get(tableProps, ['editOperasFilter', item.trigger])
  if (filter) {
    filter()
  } else {
    handler[item.trigger]()
  }
}


</script>
<template>
  <div class="y-table-edit-operas vxe-table--ignore-clear">
    <el-button v-for="(item, index) of options" :key="index" v-bind="item" link @click="handClick(item)">
      {{ item.title }}
    </el-button>
  </div>
</template>